package it.uai.domainsMigrator;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Starter {

	private static final Logger logger = Logger.getLogger(Starter.class);

	public static void main(String[] args) throws IOException,
			InterruptedException {

		PropertyConfigurator.configure("log4j.properties");

		Properties prop = new Properties();
		InputStream is = new FileInputStream(args[1]);
		prop.load(is);

		String basePath;

		if (prop.getProperty("basePath").endsWith("/")) {
			basePath = prop.getProperty("basePath");
		} else {
			basePath = prop.getProperty("basePath") + "/";
		}

		if (args[0].equalsIgnoreCase("migrator")) {

			logger.debug("Inizio processo migrator");

			DomainsManager gestoreDomini = new DomainsManager(
					prop.getProperty("domainsListFile"), basePath);

			Integer maxThread = Integer.parseInt(prop.getProperty("maxThread"));
			Integer maxItemForSingleTransfert = Integer.parseInt(prop
					.getProperty("maxItemForSingleTransfert"));
			Integer statisticsPrintPeriod = Integer.parseInt(prop
					.getProperty("statisticsPrintPeriod"));

			Domain dominio = gestoreDomini.getNextDomain();

			while (dominio != null) {

				logger.debug("Nome dominio: " + dominio.getNome());

				Controller controllore = new Controller(dominio, maxThread,
						maxItemForSingleTransfert, statisticsPrintPeriod);

				Thread tControllore = new Thread(controllore);

				tControllore.start();
				tControllore.join();

				logger.debug("Dominio processato: " + dominio.getNome());

				dominio.setProcessed();
				dominio = gestoreDomini.getNextDomain();

			}

		} else if (args[0].equalsIgnoreCase("mailer")) {

			logger.debug("Inizio processo mailer");
//			DomainsManager gestoreDomini = new DomainsManager(
//					prop.getProperty("domainsListFile"), basePath);

		}

		logger.debug("Termine processo");

	}
}
